package com.shop.service.Impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.mapper.DtsStorageMapper;
import com.shop.pojo.DtsStorage;
import com.shop.service.DtsStorageService;
import com.shop.util.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DtsStorageServiceImpl
 * @Author xiao宋
 * @Date 16:04  2022/10/17
 * @Version 1.0
 * @Description TODO
 */
@Service
public class DtsStorageServiceImpl implements DtsStorageService {
    @Autowired
    DtsStorageMapper storageMapper;
    //    服务器地址
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    //    自己创建的  Bucket  的名字
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    //    子账户密码
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    //    子账户名称
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Override
    public void delete(DtsStorage storage) {
//        先删数据库再删阿里云
        storageMapper.deleteById(storage.getId());
        AliyunOSSUtil.deleteFile(endpoint, accessKeyId, accessKeySecret, bucketName, storage.getKey());
    }

    @Override
    public DtsStorage uploadFile(String name, Integer size, String type, String objectName, byte[] bytes) throws Exception {
        String url=AliyunOSSUtil.uploadImage(endpoint, accessKeyId, accessKeySecret, bucketName, objectName, bytes);
        DtsStorage s=new DtsStorage();
        s.setUrl(url);
        s.setDeleted(false);
        s.setType(type);
        s.setSize(size);
        s.setName(name);
        s.setKey(objectName);
        s.setAddTime(new Date());
        s.setUpdateTime(new Date());
        storageMapper.insert(s);
        return s;
    }

    @Override
    public Map<String, Object> findByPage(Integer page, Integer limit, String sort, String order, String key, String name) {
        IPage<DtsStorage>iPage=new Page<>(page,limit);
        QueryWrapper<DtsStorage>w=new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            w.like("`key`", key);
        }
        if (!StringUtils.isEmpty(name)){
            w.like("`name`", name);
        }
        if ("desc".equalsIgnoreCase(order)){
            w.orderByDesc(sort);
        }else {
            w.orderByAsc(sort);
        }
        w.eq("deleted", 0);
        storageMapper.selectPage(iPage, w);
        Map<String ,Object> data = new HashMap<>();
        data.put("total", iPage.getTotal());
        data.put("items", iPage.getRecords());
        return data;
    }
}
